package cqrtplm.service.impl;

import com.google.gson.Gson;
import com.ty.basic.entity.org.UserDO;
import com.ty.basic.exception.MessageException;
import com.ty.basic.service.snow.SnowflakeIdComponent;
import com.ty.basic.session.TyAccountContext;
import cqrtplm.dto.RTCertFiledFormDTO;
import cqrtplm.dto.RTCertOAEPANewFormDTO;
import cqrtplm.dto.RTOARETDTO;
import cqrtplm.entity.*;
import cqrtplm.mapper.RTClassificationMapper;
import cqrtplm.mapper.RtCertFiledMapper;
import cqrtplm.service.*;
import cqrtplm.util.RTLogHelper;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.sql.Timestamp;
import java.util.*;
import java.util.regex.Pattern;
import java.util.stream.Collectors;
import java.util.stream.IntStream;

/**
 * 机型认证服务实现
 */
@Service
@Slf4j
public class RtCertFiledServiceImpl implements RtCertFiledService {

    @Resource
    private RtCertFiledMapper rtCertFiledMapper;

    @Resource
    private RTLogDifferenceServiceImpl rtLogDifferenceService;

    @Resource
    private SnowflakeIdComponent snowflakeIdComponent;
    @Resource
    private RtCertFiledCustomerService rtCertFiledCustomerService;

    @Resource
    private RtCertFiledPartinfoService rtCertFiledPartinfoService;

    @Resource
    private RtCertFiledPartManufacturService rtCertFiledPartManufacturService;

    @Resource
    private RtCertFiledRatoModelsService rtCertFiledRatoModelsService;

    @Resource
    private RtComSupplierService rtComSupplierService;

    @Resource
    private RTClassificationMapper rtClassificationMapper;

    @Resource
    private RTLogHelper rtLogHelper;
    private Map<String, String> allSupplierMap;

    @Override
    public List<RtCertFiledDO> selectRtCertFiledList(RtCertFiledDO rtCertFiled) {
        return rtCertFiledMapper.selectRtCertFiledList(rtCertFiled);
    }

    @Override
    public RtCertFiledDO selectRtCertFiledById(String id) {
        return rtCertFiledMapper.selectRtCertFiledById(id);
    }

    @Override
    public RTCertFiledFormDTO selectRtCertFiledAllDataById(String id) {
        RTCertFiledFormDTO rtCertFiled = new RTCertFiledFormDTO();
        rtCertFiled.setId(id);
        rtCertFiled.setAction("get");
        rtCertFiled.setRtCertFiledDO(rtCertFiledMapper.selectRtCertFiledById(id));

        RtCertFiledCustomerDO rtCertFiledCustomerDO = new RtCertFiledCustomerDO();
        rtCertFiledCustomerDO.setFiledId(id);
        rtCertFiled.setCustomerlist(
                rtCertFiledCustomerService.selectRtCertFiledCustomerList(rtCertFiledCustomerDO)
        );

        RtCertFiledRatoModelsDO rtCertFiledRatoModelsDO = new RtCertFiledRatoModelsDO();
        rtCertFiledRatoModelsDO.setFiledId(id);
        rtCertFiled.setRatoModelslist(
                rtCertFiledRatoModelsService.selectRtCertFiledRatoModelsList(rtCertFiledRatoModelsDO));

        List<RtCertFiledPartManufacturDO> mlist = rtCertFiledPartManufacturService.selectRtCertFiledPartManufacturByFiledId(
                id);

        //partid为空的供应商信息
        rtCertFiled.setManufacturerlist(
                mlist.stream()
                        .filter(m -> m.getPartId() == null)
                        .collect(Collectors.toList())
        );


        Map<String, List<RtCertFiledPartManufacturDO>> manufacturerMap = mlist.stream()
                .filter(m -> m.getPartId() != null)
                .collect(Collectors.groupingBy(RtCertFiledPartManufacturDO::getPartId));

        RtCertFiledPartinfoDO rtCertFiledPartinfoDO = new RtCertFiledPartinfoDO();
        rtCertFiledPartinfoDO.setFiledId(id);
        List<RtCertFiledPartinfoDO> partinfoList = rtCertFiledPartinfoService.selectRtCertFiledPartinfoList(
                rtCertFiledPartinfoDO);

        partinfoList.forEach(item -> {
            item.setManufacturerlist(manufacturerMap.getOrDefault(item.getId(), Collections.emptyList()));
        });

        rtCertFiled.setPartlist(partinfoList);

        //        RtCertFiledPartManufacturDO rtCertFiledPartManufacturDO = new RtCertFiledPartManufacturDO();
        //        rtCertFiledPartManufacturDO.setFiledId(id);
        //        rtCertFiledPartManufacturDO.setPartId(null);
        //        rtCertFiled.setManufacturerlist(rtCertFiledPartManufacturService.selectRtCertFiledPartManufacturList(rtCertFiledPartManufacturDO));


        return rtCertFiled;
    }

    @Override
    public List<RtCertFiledDO> selectRtCertFiledByModelCtype(String model, String ctype) {
        return rtCertFiledMapper.selectRtCertFiledByModelCtype(model, ctype);
    }

    @Override
    @Transactional
    public int insertRtCertFiled(RtCertFiledDO rtCertFiled) {
        String model = rtCertFiled.getModel();
        String ctype = rtCertFiled.getCtype();
        List<RtCertFiledDO> old = rtCertFiledMapper.selectRtCertFiledByModelCtype(model, ctype);
        if (old != null && !old.isEmpty()) {
            //throw RTErrorCodeEnum.CERT_FILED_EXISTS.getException("该型号已存在，请勿重复添加");
            throw new MessageException("该型号已存在，请勿重复添加");
        } else {
            UserDO user = TyAccountContext.getUser();
            if (user == null) {
                throw new RuntimeException("用户未登录");
            }

            String snowId = String.valueOf(snowflakeIdComponent.getInstance().nextId());
            Timestamp timestamp = new Timestamp(new Date().getTime());

            rtCertFiled.setId(snowId);
            rtCertFiled.setCreatetime(timestamp);
            rtCertFiled.setCreateuserid(String.valueOf(user.getOid()));
            rtCertFiled.setCreateusername(user.getName());

            rtLogDifferenceService.newLog(
                    rtCertFiled, null,
                    rtCertFiled.getId(),
                    user.getName(),
                    "机型认证",
                    "新建",
                    ""
            );

            //            log.info("机型认证-新增{},{},{},{}",
            //                     rtCertFiled.getModel(),
            //                     snowId,
            //                     timestamp,
            //                     user.getName());

            return rtCertFiledMapper.insertRtCertFiled(rtCertFiled);
        }
    }

    @Override
    @Transactional
    public int updateRtCertFiled(RtCertFiledDO rtCertFiled) {
        RtCertFiledDO old = rtCertFiledMapper.selectRtCertFiledById(rtCertFiled.getId());
        if (old == null) {
            throw new MessageException("该机型认证不存在，请检查");
        } else {
            UserDO user = TyAccountContext.getUser();
            if (user == null) {
                throw new RuntimeException("用户未登录");
            }

            Timestamp timestamp = new Timestamp(new Date().getTime());
            rtCertFiled.setUpdatetime(timestamp);
            rtCertFiled.setUpdateuserid(String.valueOf(user.getOid()));
            rtCertFiled.setUpdateusername(user.getName());

            int r = rtCertFiledMapper.updateRtCertFiled(rtCertFiled);
            if (r > 0) {
                // 记录差异日志
                rtLogDifferenceService.newLog(
                        rtCertFiled, old,
                        rtCertFiled.getId(),
                        user.getName(),
                        "机型认证",
                        "修改",
                        ""
                );
            }
            return r;
        }
    }

    @Override
    @Transactional
    public int deleteRtCertFiledById(String id) {
        rtCertFiledCustomerService.deleteRtCertFiledCustomerByFiledId(id);
        rtCertFiledPartinfoService.deleteRtCertFiledPartinfoByFiledId(id);
        rtCertFiledPartManufacturService.deleteRtCertFiledPartManufacturByFiledId(id);
        rtCertFiledRatoModelsService.deleteRtCertFiledRatoModelsByFiledId(id);

        return rtCertFiledMapper.deleteRtCertFiledById(id);
    }

    @Override
    @Transactional
    public int deleteRtCertFiledByIds(List<String> ids) {

        ids.forEach(id -> {
            deleteRtCertFiledById(id);
        });
        return 1;
    }

    @Override
    @Transactional
    public String save(RTCertFiledFormDTO postdata) {
        if ("add".equals(postdata.getAction())) {

            insertRtCertFiled(postdata.getRtCertFiledDO());

            List<RtCertFiledCustomerDO> customerlist = postdata.getCustomerlist();
            for (RtCertFiledCustomerDO customer : customerlist) {
                customer.setFiledId(postdata.getRtCertFiledDO().getId());
                customer.setCtype(postdata.getRtCertFiledDO().getCtype());
                customer.setModel(postdata.getRtCertFiledDO().getModel());
                rtCertFiledCustomerService.insertRtCertFiledCustomer(customer);
            }

            List<RtCertFiledPartinfoDO> partlist = postdata.getPartlist();

            // 去重
            Map<String, RtCertFiledPartinfoDO> distinctpartlist = new LinkedHashMap<>();
            for (RtCertFiledPartinfoDO item : partlist) {
                distinctpartlist.putIfAbsent(item.getPartNo(), item);
            }
            for (RtCertFiledPartinfoDO part : distinctpartlist.values()) {
                part.setFiledId(postdata.getRtCertFiledDO().getId());
                String partID = rtCertFiledPartinfoService.insertRtCertFiledPartinfo(part);
            }

            List<RtCertFiledPartManufacturDO> manufacturerlist = postdata.getManufacturerlist();
            for (RtCertFiledPartManufacturDO manufacturer : manufacturerlist) {
                manufacturer.setFiledId(postdata.getRtCertFiledDO().getId());
                manufacturer.setPartId(null);
                rtCertFiledPartManufacturService.insertRtCertFiledPartManufactur(manufacturer);
            }

            List<RtCertFiledRatoModelsDO> ratoModelslist = postdata.getRatoModelslist();
            // 去重
            Map<String, RtCertFiledRatoModelsDO> distinctModels = new LinkedHashMap<>();
            for (RtCertFiledRatoModelsDO model : ratoModelslist) {
                distinctModels.putIfAbsent(model.getDevCode(), model);
            }
            for (RtCertFiledRatoModelsDO model : distinctModels.values()) {
                model.setFiledId(postdata.getRtCertFiledDO().getId());
                rtCertFiledRatoModelsService.insertRtCertFiledRatoModels(model);
            }

            return postdata.getRtCertFiledDO().getId();

        } else if ("edit".equals(postdata.getAction())) {

            updateRtCertFiled(postdata.getRtCertFiledDO());

            List<RtCertFiledCustomerDO> customerlist = postdata.getCustomerlist();
            rtCertFiledCustomerService.updateEntityList(
                    postdata,
                    customerlist
            );

            List<RtCertFiledPartinfoDO> partlist = postdata.getPartlist();
            rtCertFiledPartinfoService.updateEntityList(
                    postdata,
                    partlist
            );

            List<RtCertFiledPartManufacturDO> manufacturerlist = postdata.getManufacturerlist();
            rtCertFiledPartManufacturService.updateEntityList(
                    postdata,
                    null,
                    manufacturerlist
            );

            List<RtCertFiledRatoModelsDO> ratoModelslist = postdata.getRatoModelslist();
            rtCertFiledRatoModelsService.updateEntityList(
                    postdata,
                    ratoModelslist
            );

            return postdata.getRtCertFiledDO().getId();
        } else {
            throw new MessageException("未知操作");
        }
    }

    @Override
    public List<RTProductDevelopmentOrderDO> getDevCode(RTProductDevelopmentOrderDO entity) {
        return rtClassificationMapper.selectRtCfgProductDevelopmentOrderList(entity);
    }

    @Override
    public RTOARETDTO oasave(RTCertOAEPANewFormDTO postdata) {

        RTOARETDTO ret = new RTOARETDTO();
        try {
        String ctype = postdata.getCtype();
        String model = postdata.getModel();
        String filedID = null;
        String action = null;
        List<RtCertFiledDO> filedlist = this.selectRtCertFiledByModelCtype(model, ctype);
        if (filedlist.size() > 0) {
            filedID = filedlist.get(0).getId();
            action = "edit";
        } else {
            action = "add";
        }

        String logtitle = "OA接口EPA认证新增:"+postdata.getOaformno();
        log.info(logtitle,postdata);

        List<RtComSupplierDO> allSupplierlist = rtComSupplierService.selectRtComSupplierList(new RtComSupplierDO());
        allSupplierMap = allSupplierlist.stream()
                .collect(Collectors.toMap(
                        RtComSupplierDO::getSupplierCode,
                        RtComSupplierDO::getShortName
                ));

        Gson gson = new Gson();
        // 对象转JSON字符串
        String json = gson.toJson(postdata);
        // JSON字符串转另一个对象
        RtCertFiledDO filedEntity = gson.fromJson(json, RtCertFiledDO.class);
        filedEntity.setId(filedID);


        //基础信息和参数信息
        RTCertFiledFormDTO filedFormDTO = new RTCertFiledFormDTO();
        filedFormDTO.setId(filedID);
        filedFormDTO.setAction(action);
        filedFormDTO.setRtCertFiledDO(filedEntity);
        filedFormDTO.setEditWithoutDelete(true);

        //公司机型
        List<RtCertFiledRatoModelsDO> ratoModelslist = new ArrayList<RtCertFiledRatoModelsDO>();
        RtCertFiledRatoModelsDO ratoModels = new RtCertFiledRatoModelsDO();
        ratoModels.setDevCode(postdata.getRatodevcode());
        ratoModelslist.add(ratoModels);

        //客户信息
        List<RtCertFiledCustomerDO> customerlist = new ArrayList<RtCertFiledCustomerDO>();
        RtCertFiledCustomerDO customer = new RtCertFiledCustomerDO();
        customer.setKhmc(postdata.getKhmc());
        customer.setModel(model);
        customer.setCtype(ctype);
        customer.setFiledId(filedFormDTO.getId());
        customerlist.add(customer);


        //处理化油器厂家 化油器厂家绑定到表单上而非件号
        List<RtCertFiledPartManufacturDO> manufacturerlist = new ArrayList<RtCertFiledPartManufacturDO>();

        if (postdata.getPartnoHyqCJ()!=null && !postdata.getPartnoHyqCJ().isEmpty()) {
            postdata.getPartnoHyqCJ().forEach(cjID -> {
                if (!cjID.isEmpty() && !cjID.trim().equals("/") && !cjID.trim().equals("\\")) {
                    RtCertFiledPartManufacturDO manufacturer = new RtCertFiledPartManufacturDO();
                    manufacturer.setFiledId(filedFormDTO.getId());
                    manufacturer.setPartCode("16100");
                    manufacturer.setManufacturerId(cjID);

                    String cjName = allSupplierMap.getOrDefault(cjID, "待同步");
                    manufacturer.setManufacturer(cjName);

                    manufacturerlist.add(manufacturer);
                }
            });
        }
        if (postdata.getHyqxhscc()!=null
                && !postdata.getHyqxhscc().isEmpty()
                && !postdata.getHyqxhscc().trim().equals("null")) {
            String[] cjIDString = postdata.getHyqxhscc().split(",");
            for (String cjID : cjIDString) {
                if (!cjID.isEmpty() && !cjID.trim().equals("/") && !cjID.trim().equals("\\")) {

                    RtCertFiledPartManufacturDO manufacturer = new RtCertFiledPartManufacturDO();
                    manufacturer.setFiledId(filedFormDTO.getId());
                    manufacturer.setPartCode("16100");
                    manufacturer.setManufacturerId(cjID);
                    String cjName = allSupplierMap.getOrDefault(cjID, "待同步");
                    manufacturer.setManufacturer(cjName);

                    manufacturerlist.add(manufacturer);
                }
            }
        }


        //处理零部件
        List<RtCertFiledPartinfoDO> partlist = new ArrayList<RtCertFiledPartinfoDO>();
        //化油器
        handlePartListSimple("尾气", filedEntity, partlist, postdata.getPartnoHyq(), null, null);
        // 空滤器
        handlePartListSimple("尾气", filedEntity, partlist, postdata.getPartnoKlq(), null, null);
        //消声器
        handlePartListSimple("尾气", filedEntity, partlist, postdata.getPartnoXsq(), null, null);
        //点火线圈
        handlePartListSimple("尾气", filedEntity, partlist, postdata.getPartnoDhxq(), null, null);
        //火花塞
        handlePartListSimple("尾气", filedEntity, partlist, postdata.getPartnoHhs(), null, null);
        //呼吸片
        handlePartListSimple("尾气", filedEntity, partlist, postdata.getPartnoHxp(), null, null);
        //海拔-低海拔
        handlePartListSimple("低海拔", filedEntity, partlist, postdata.getPartnoHaibadi(), null, null);
        //海拔-高海拔
        handlePartListSimple("高海拔", filedEntity, partlist, postdata.getPartnoHaibagao(), null, null);

        //触媒
        handlePartListSimple("触媒", filedEntity, partlist, postdata.getPartnoCm(), postdata.getCjCm(), null);
        //二次补气阀
        handlePartListSimple("二次补气阀", filedEntity, partlist, postdata.getPartnoEcbqf(), null, null);
        //ECU
        handlePartListSimple("ECU", filedEntity, partlist, postdata.getPartnoEcu(), postdata.getCjECU(), null);
        //ECU油泵
        handlePartListSimple("尾气", filedEntity, partlist, postdata.getPartnoEcuyb(), null, postdata.getPartnoEcu());
        //O2
        handlePartListSimple("O2", filedEntity, partlist, postdata.getPartnoO2(), null, null);
        //机组消声器
        handlePartListSimple("机组消声器", filedEntity, partlist, postdata.getPartnoJzxsq(), null, null);

        //发动机蒸发
        handlePartListZhengFa("发动机蒸发", filedEntity, partlist,
                              null,
                              postdata.getPartnoFdongjyx(),
                              postdata.getPartnoFdongjyxgg(),
                              postdata.getPartnoFdongjyxcz(),
                              postdata.getPartnoFdongjyxcj(),
                              postdata.getPartnoFdongjyxg(),
                              postdata.getPartnoFdongjyggg(),
                              postdata.getPartnoFdongjygcj(),
                              postdata.getPartnoFdongjtg(),
                              postdata.getPartnoFdongjtgcj(),
                              postdata.getPartnoFdongjtgzsh());
        //发电机蒸发
        handlePartListZhengFa("发电机蒸发", filedEntity, partlist,
                              postdata.getPartnoFdianjjzxh(),
                              postdata.getPartnoFdianjyx(),
                              postdata.getPartnoFdianjyxgg(),
                              postdata.getPartnoFdianjyxcz(),
                              postdata.getPartnoFdianjyxcj(),
                              postdata.getPartnoFdianjyxg(),
                              postdata.getPartnoFdianjyggg(),
                              postdata.getPartnoFdianjygcj(),
                              postdata.getPartnoFdianjtg(),
                              postdata.getPartnoFdianjtgcj(),
                              postdata.getPartnoFdianjtgzsh());


        filedFormDTO.setPartlist(partlist);
        filedFormDTO.setCustomerlist(customerlist);
        filedFormDTO.setRatoModelslist(ratoModelslist);
        filedFormDTO.setManufacturerlist(manufacturerlist);

        this.save(filedFormDTO);

            ret.setSuccess(true);
            ret.setMessage("保存成功");
            return ret;
        } catch (Exception e) {
            e.printStackTrace();
            ret.setSuccess(false);
            ret.setMessage("保存到PLM时出错了:"+e.getMessage());
        }
        return ret;
    }

    private void handlePartListSimple(String tableName
            , RtCertFiledDO rtCertFiled
            , List<RtCertFiledPartinfoDO> partlist
            , List<String> partNolist
            , List<String> partManufacturlist
            , List<String> referPartNolist
    ) {
        for (int i = 0; i < partNolist.size(); i++) {
            String partno = partNolist.get(i);
            if (partno == null || partno.isEmpty() || partno.trim().equals("/")
                    || partno.trim().equals("\\") ||  partno.trim().equals("无")
                    || partno.trim().equals("null")
            ) {
                continue;
            }else{
                partno=this.CheckPartNo(partno.trim().toUpperCase());
            }
//            if (partno == null || partno.length() < 9) {
//                continue;
//            }
            RtCertFiledPartinfoDO part = new RtCertFiledPartinfoDO();

            //根据partno查询同表单是否已存在件号
            RtCertFiledPartinfoDO queryOldPartinfoDO = new RtCertFiledPartinfoDO();
            queryOldPartinfoDO.setPartNo(partno);
            queryOldPartinfoDO.setFiledId(rtCertFiled.getId());
            RtCertFiledPartinfoDO oldPart = rtCertFiledPartinfoService.selectRtCertFiledPartinfoByDO(
                    queryOldPartinfoDO);
            String partid = null;
            if (oldPart != null) {
                partid = oldPart.getId();
            } else {
                partid = String.valueOf(snowflakeIdComponent.getInstance().nextId());
            }
            part.setId(partid);

            switch (tableName) {
                case "低海拔":
                    part.setTableName("尾气");
                    part.setAltitude("3000-6000ft");
                    break;
                case "高海拔":
                    part.setTableName("尾气");
                    part.setAltitude("6000-8000ft");
                    break;
                case "尾气":
                default:
                    part.setTableName(tableName);
                    part.setAltitude("");
                    break;
            }

            part.setPartNo(partno);
            part.setFiledId(rtCertFiled.getId());
            part.setPartCode(partno.substring(0, 5));

            if (referPartNolist != null && !referPartNolist.isEmpty()) {
                part.setRelatedPartNo(referPartNolist.get(i));
            }

            List<RtCertFiledPartManufacturDO> cjlist = new ArrayList<>();
            if (partManufacturlist != null && partManufacturlist.size() == partNolist.size()) {
                if (!partManufacturlist.get(i).isEmpty()) {
                    String[] cjIDString = partManufacturlist.get(i).split(",");
                    for (String cjID : cjIDString) {
                        if (!cjID.isEmpty() && !cjID.trim().equals("/") && !cjID.trim().equals("\\")) {
                            String cjName = allSupplierMap.getOrDefault(cjID, "待同步");
                            RtCertFiledPartManufacturDO cj = new RtCertFiledPartManufacturDO();
                            cj.setFiledId(rtCertFiled.getId());
                            cj.setPartId(part.getId());
                            cj.setPartCode(null);
                            cj.setManufacturerId(cjID);
                            cj.setManufacturer(cjName);
                            cjlist.add(cj);
                        }
                    }
                }

            }
            if (!cjlist.isEmpty()) {
                part.setManufacturerlist(cjlist);
            }
            partlist.add(part);
        }
    }

    private String CheckPartNo(String partno) {
        Pattern pattern = Pattern.compile("^\\d{5}-[A-Za-z0-9]{3}\\d{2}$");
        if(!pattern.matcher(partno).matches())
        {
            throw new RuntimeException(partno+"不符合11位图号规则");
        }
        return partno.toUpperCase();
    }

    private void handlePartListZhengFa(String tableName
            , RtCertFiledDO rtCertFiled
            , List<RtCertFiledPartinfoDO> partlist
            , List<String> jzxh    //机组型号
            , List<String> yx      //油箱件号
            , List<String> yxgg    //规格
            , List<String> yxcz    //油箱材质
            , List<String> yxcj    //油箱厂家
            , List<String> yxg     //油箱盖件号
            , List<String> yggg    //油管规格
            , List<String> ygcj    //油管厂家
            , List<String> tg      //碳罐件号
            , List<String> tgcj    //碳罐厂家
            , List<String> tgzsh   //碳罐证书
    ) {


        for (int i = 0; i < yx.size(); i++) {
            String partno = yx.get(i);
            String terminalType = null;
            if (jzxh != null && !jzxh.isEmpty()) {
                terminalType = jzxh.get(i);
            }
            String yxspec = yxgg.get(i);
            String yxmaterial = yxcz.get(i);
            String yxmanufacturer = yxcj.get(i);

            String yxgpartno = yxg.get(i);

            String ygspec = yggg.get(i);
            String ygmanufacturer = ygcj.get(i);

            String tgpartno = tg.get(i).toUpperCase();
            String tgmanufacturer = tgcj.get(i);
            String tgzs = tgzsh.get(i);

            //            if(partno==null || partno.length()<9){
            //                continue;
            //            }

            //油箱
            if (partno != null && partno.length() > 8) {
                String partCode = partno.substring(0, 5);
                RtCertFiledPartinfoDO part = createSiglePart(tableName, rtCertFiled, partno, partCode, yxmanufacturer,
                                                             yxspec, yxmaterial, terminalType, null, null);
                if (part != null) {
                    partlist.add(part);
                }
            }

            //油箱盖
            if (yxgpartno != null && yxgpartno.length() > 8) {
                String partCode = yxgpartno.substring(0, 5);
                RtCertFiledPartinfoDO part = createSiglePart(tableName, rtCertFiled, yxgpartno, partCode, null, null,
                                                             null, terminalType, null, partno);
                if (part != null) {
                    partlist.add(part);
                }
            }

            //油管
            if (partno != null && partno.length() > 8) {
                if (!ygspec.isEmpty() && !ygspec.equals("/") && !ygspec.equals("\\")) {
                    String ygno = partno + "_油管";
                    String partCode = "90686";
                    RtCertFiledPartinfoDO part = createSiglePart(tableName, rtCertFiled, ygno, partCode, ygmanufacturer,
                                                                 null, null, terminalType, null, partno);
                    if (part != null) {
                        partlist.add(part);
                    }
                }
            }
            //碳罐
            if (tgpartno != null && tgpartno.length() > 8) {
                String partCode = tgpartno.substring(0, 5);
                RtCertFiledPartinfoDO part = createSiglePart(tableName, rtCertFiled, tgpartno, partCode, tgmanufacturer,
                                                             null, null, terminalType, tgzs, partno);
                if (part != null) {
                    partlist.add(part);
                }
            }


        }
    }


    private RtCertFiledPartinfoDO createSiglePart(String tableName
            , RtCertFiledDO rtCertFiled
            , String partNo
            , String partCode
            , String partManufacturIDs
            , String partSpec
            , String partMaterial
            , String partTerminalType
            , String partCertificate_number
            , String referPartNo
    ) {

        if (partNo == null || partNo.isEmpty() || partNo.trim().equals("/")
                || partNo.trim().equals("\\") ||  partNo.trim().equals("无")
                || partNo.trim().equals("null")
        ) {
            return null;
        }else{
            partNo=this.CheckPartNo(partNo.trim().toUpperCase());
        }

        RtCertFiledPartinfoDO part;
        String partid;

        //根据partno查询同表单是否已存在件号
        RtCertFiledPartinfoDO queryOldPartinfoDO = new RtCertFiledPartinfoDO();
        queryOldPartinfoDO.setPartNo(partNo);
        queryOldPartinfoDO.setFiledId(rtCertFiled.getId());
        RtCertFiledPartinfoDO oldPart = rtCertFiledPartinfoService.selectRtCertFiledPartinfoByDO(queryOldPartinfoDO);

        if (oldPart != null) {
            part = oldPart;
        } else {
            if (partNo.isEmpty() || partNo.trim().equals("/") || partNo.trim().equals("\\")) {
                return null;
            }
            part = new RtCertFiledPartinfoDO();
            partid = String.valueOf(snowflakeIdComponent.getInstance().nextId());
            part.setId(partid);
            part.setPartNo(partNo);
        }

        part.setFiledId(rtCertFiled.getId());
        part.setPartCode(partCode);
        part.setSpecification(partSpec);
        part.setMaterial(partMaterial);
        part.setTerminalType(partTerminalType);
        part.setCertificateNumber(partCertificate_number);


        if (referPartNo != null && !referPartNo.isEmpty()) {
            part.setRelatedPartNo(referPartNo);
        }

        List<RtCertFiledPartManufacturDO> cjlist = new ArrayList<>();
        if (!partManufacturIDs.isEmpty()) {
            String[] cjIDString = partManufacturIDs.split(",");
            for (String cjID : cjIDString) {
                if (!cjID.isEmpty() && !cjID.trim().equals("/") && !cjID.trim().equals("\\")) {
                    RtCertFiledPartManufacturDO queryOldManufacturDO = new RtCertFiledPartManufacturDO();
                    queryOldManufacturDO.setPartId(part.getId());
                    queryOldManufacturDO.setManufacturerId(cjID);
                    List<RtCertFiledPartManufacturDO> oldlist = rtCertFiledPartManufacturService.selectRtCertFiledPartManufacturList(
                            queryOldManufacturDO);

                    //只有新供应商才从oa添加 历史的不变
                    if (oldlist.isEmpty()) {
                        String cjName = allSupplierMap.getOrDefault(cjID, "待同步");

                        RtCertFiledPartManufacturDO cj = new RtCertFiledPartManufacturDO();
                        cj.setFiledId(rtCertFiled.getId());
                        cj.setPartId(part.getId());
                        cj.setPartCode(null);
                        cj.setManufacturerId(cjID);
                        cj.setManufacturer(cjName);
                        cjlist.add(cj);
                    }
                }
            }
        }

        if (!cjlist.isEmpty()) {
            part.setManufacturerlist(cjlist);
        }
        return part;
    }
}